package com.jsz.peini.controller.pay;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.ResourceBundle;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.jsz.peini.bean.activity.ActivityInfo;
import com.jsz.peini.bean.order.OrderInfo;
import com.jsz.peini.bean.order.OrderInfoExample;
import com.jsz.peini.bean.order.PayStream;
import com.jsz.peini.bean.seller.SellerInfo;
import com.jsz.peini.bean.task.TaskInfo;
import com.jsz.peini.bean.user.UserInfo;
import com.jsz.peini.common.constants.Constants;
import com.jsz.peini.common.meta.OrderType;
import com.jsz.peini.common.util.DateTimeUtils;
import com.jsz.peini.common.util.PeiniUtils;
import com.jsz.peini.common.util.wxpay.GetWxOrderno;
import com.jsz.peini.common.util.wxpay.RequestHandler;
import com.jsz.peini.common.util.wxpay.ResponseHandler;
import com.jsz.peini.common.util.wxpay.Sha1Util;
import com.jsz.peini.common.util.wxpay.XMLUtil;
import com.jsz.peini.common.util.wxpay.query.QueryWeChatPayOrderReqModel;
import com.jsz.peini.common.util.wxpay.query.QueryWeChatPayOrderResModel;
import com.jsz.peini.common.util.wxpay.query.WeChatUtil;
import com.jsz.peini.mapper.activity.ActivityInfoMapper;
import com.jsz.peini.mapper.order.OrderInfoMapper;
import com.jsz.peini.mapper.order.PayStreamMapper;
import com.jsz.peini.mapper.seller.SellerInfoMapper;
import com.jsz.peini.mapper.task.TaskInfoMapper;
import com.jsz.peini.mapper.user.UserInfoMapper;
import com.jsz.peini.service.order.OrderInfoService;
import com.jsz.peini.service.task.PartyService;


/**
 * 微信支付
 * @author Han Guohong
 *
 */
@Controller
@RequestMapping("/payWx")
public class PayByWxController {
	private static final Logger logger = LoggerFactory.getLogger(PayByWxController.class);
	@Resource
	private PayStreamMapper payStreamMapper;
	@Resource
	private OrderInfoMapper orderInfoMapper;
	@Resource
	private TaskInfoMapper taskInfoMapper;
	@Resource
	private UserInfoMapper userInfoMapper;
	@Resource
	private OrderInfoService orderInfoService;
	@Resource
	private SellerInfoMapper sellerInfoMapper;
	@Resource
	private ActivityInfoMapper activityInfoMapper;
	@Resource
	private PartyService partyService;
	
	@ResponseBody
	@RequestMapping(value = "/prePay",produces="text/plain;charset=UTF-8")
	public String prePay(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value="orderIdStr",required=true) String orderId,
			@RequestParam(value="userId",required=true) String token,
			@RequestParam(value="trade_type",required=false,defaultValue="APP") String trade_type
			) throws Exception{
		
		//logger.info(PropertiesUtil.getKey("host"));
		
		logger.info("*****************APP发起微信支付*******************");
		JSONObject object = new JSONObject();
		
		try{
			if(StringUtils.isEmpty(orderId)){
				object.put("resultCode", "0");
				object.put("resultDesc", "订单号不能为空");
				return object.toString();
			}
			
			if(StringUtils.isBlank(token)){
				object.put("resultCode", Constants.EXCEPTION);
				object.put("resultDesc", Constants.EXCEPTION_DESC);
				return object.toString();
			}
			
			if(StringUtils.isBlank(trade_type)){
				trade_type = "APP";
			}
			
			JSONObject obj = PeiniUtils.validToken(token);
			if(obj.getInteger("resultCode") != 1){
				return obj.toJSONString();
			}
			String userId = obj.getString("userId");
			
			if(orderId.endsWith(",")){
				orderId = orderId.substring(0, orderId.length()-1);
			}
			
			OrderInfo title = orderInfoMapper.selectByPrimaryKey(Long.parseLong(orderId));
			String orderCode = title.getOrderCode();
			if(StringUtils.isBlank(orderCode)){
				orderCode = title.getId().toString();
			}
			
			PayStream payStream = new PayStream();
			String payId = "";
			
			payStream = payStreamMapper.selectByPrimaryKey(orderCode);
			if(payStream != null){//支付流水已经创建过 
				if(payStream.getPayStatus() == 1){
					object.put("resultCode", "0");
					object.put("resultDesc", "该订单已经支付过啦，请勿重复支付");
					return object.toString();
				}else{
					/*payStream.setPayTime(new Date());
					payId = payStream.getPayId();*/
					
					payStream = new PayStream();
					payId = title.getPayStreamId()+"0";
					payStream.setPayStatus(0);
					payStream.setUserId(userId);
					payStream.setPayTime(new Date());
					payStream.setOrderIdsStr(orderId);
					payStream.setPayId(payId);
					PayStream payStreamTmp = payStreamMapper.selectByPrimaryKey(payId);
					if(payStreamTmp==null){
						payStreamMapper.insertSelective(payStream);
					}else{
						logger.info("重复的订单号====payId>>>"+payId);
					}
				}
			}else{
				payStream = new PayStream();
				payId = orderCode;
				payStream.setPayStatus(0);
				// payStream.setPayType(2);
				payStream.setUserId(userId);
				payStream.setPayTime(new Date());
				payStream.setOrderIdsStr(orderId);
				//payId = UUID.randomUUID().toString().replace("-", "");
				payStream.setPayId(orderCode);
				payStreamMapper.insertSelective(payStream);
			}
						
			String bodyStr = "";
			String titleStr = "";
			//Double totalPay = 0.00;
			BigDecimal totalPay = new BigDecimal("0");
					
			Integer orderType = title.getOrderType();
			
			if(orderType == 1){//任务订单
				int taskId = title.getTaskInfoId();
				TaskInfo taskInfo = taskInfoMapper.selectByPrimaryKey(taskId);
				titleStr = "任务消费：";
				titleStr += taskInfo.getSellerInfoName();
				if(taskInfo.getUserId().equals(userId)){
					String otherUserId = taskInfo.getOtherUserId();
					UserInfo userInfo = userInfoMapper.selectByPrimaryKey(otherUserId);
					bodyStr = DateTimeUtils.formatDateTime2String(taskInfo.getTaskAppointedTime(), "yyyy-MM-dd HH:mm")+"和"+userInfo.getNickname()+"约会";
				}else{
					String otherUserId = taskInfo.getUserId();
					UserInfo userInfo = userInfoMapper.selectByPrimaryKey(otherUserId);
					bodyStr = DateTimeUtils.formatDateTime2String(taskInfo.getTaskAppointedTime(), "yyyy-MM-dd HH:mm")+"和"+userInfo.getNickname()+"约会";
				}
			}else if(orderType == 2){//任务订单
				
			}else if (orderType == 3) {// 普通商家订单
				titleStr = "商家消费：";
				int sellerId = title.getSellerInfoId();
				SellerInfo sellerInfo = sellerInfoMapper.selectByPrimaryKey(sellerId);
				bodyStr = DateTimeUtils.formatDateTime2String(title.getOrderTime(),"yyyy-MM-dd HH:mm")+" "+sellerInfo.getSellerName();
			}else if (orderType == 4) {// 任务评价打赏订单
				titleStr = "打赏：";
				String otherId = title.getOtherId();
				UserInfo userInfo = userInfoMapper.selectByPrimaryKey(otherId);
				bodyStr = DateTimeUtils.formatDateTime2String(title.getOrderTime(),"yyyy-MM-dd HH:mm")+" "+userInfo.getNickname();
			}else if (orderType == 6) {// 金币充值订单
				titleStr = "金币充值：";
				bodyStr = DateTimeUtils.formatDateTime2String(title.getOrderTime(),"yyyy-MM-dd HH:mm")+" "+title.getPayMoney();
			}else if (orderType == 7) {// 活动报名订单
				titleStr = "活动报名：";
				String acId = title.getParamId();
				ActivityInfo acInfo = activityInfoMapper.selectByPrimaryKey(acId);
				bodyStr = acInfo.getAcTitle()+"："+DateTimeUtils.formatDateTime2String(title.getOrderTime(),"yyyy-MM-dd HH:mm")+" "+title.getPayMoney();
			}else if(orderType == OrderType.PARTY_PREPAY){
				titleStr = "聚会预付款：";
				bodyStr = DateTimeUtils.formatDateTime2String(title.getOrderTime(),"yyyy-MM-dd HH:mm")+" "+title.getPayMoney();
			}else if(orderType == OrderType.PARTY_ORDER){
				titleStr = "聚会付款：";
				bodyStr = DateTimeUtils.formatDateTime2String(title.getOrderTime(),"yyyy-MM-dd HH:mm")+" "+title.getPayMoney();
			}else if(orderType == OrderType.OFFICAL_PARTY){
				titleStr = "官方聚会付款：";
				bodyStr = DateTimeUtils.formatDateTime2String(title.getOrderTime(),"yyyy-MM-dd HH:mm")+" "+title.getPayMoney();
			}
			
			//totalPay = ((double)title.getPayMoney())/100;
			totalPay = new BigDecimal(title.getPayMoney()).divide(new BigDecimal("100"));
			
			title.setPayType(2);
			title.setPayStatus(0);
			title.setPayStreamId(payId);
			orderInfoMapper.updateByPrimaryKeySelective(title);
				
			if(titleStr.length()>100){
				titleStr = titleStr.substring(0, 100);
			}
			
			//payStream.setPayMoney(totalPay);
			payStream.setPayMoney(totalPay.doubleValue());
			payStream.setPayCode(UUID.randomUUID().toString().replace("-", ""));
			payStreamMapper.updateByPrimaryKey(payStream);
			
			JSONObject dataObj = new JSONObject();
			dataObj.put("title", titleStr);
			dataObj.put("detail", bodyStr);
			dataObj.put("payPrice", totalPay);
			dataObj.put("orderCode", payId);
			
			return getWxOrder(dataObj, token, request, response, trade_type);
		}catch(Exception e){
			return null;
		}
	}
	
	/**
	 * 接收微信支付的异步通知消息
	 * @author Han Guohong
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/notify",produces="text/plain;charset=UTF-8")
	public String notify(HttpServletRequest request,HttpServletResponse response) throws Exception{
		logger.info("-----------------------------收到微信回调------------------------------------------------------");
		BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while((line = br.readLine())!=null){
            sb.append(line);
        }
        try {
    		Double bossValue=0d;
    		logger.info(sb.toString());
			Map<String, String> map = XMLUtil.doXMLParse(sb.toString());
			// ---------------------------------------------------------
			// 创建支付应答对象
			ResponseHandler resHandler = new ResponseHandler(request, response);
			String appid = map.get("appid");
			
			ResourceBundle PropertiesUtil = ResourceBundle.getBundle("config");
			String pay_key = PropertiesUtil.getString("wxapppay_paykey");
			
			String return_code = map.get("return_code");
			
			if(StringUtils.isNotEmpty(return_code)&&return_code.equals("SUCCESS")){
				// 创建请求对象
				if (resHandler.isValidSign(map,pay_key) == true) {
					// 商户订单号
					String out_trade_no = map.get("out_trade_no");
					// 腾讯订单号
					String transaction_id = map.get("transaction_id");
					// 金额,以分为单位
					String total_fee = map.get("total_fee");
					// 如果有使用折扣券，discount有值，total_fee+discount=原请求的total_fee
					String discount = map.get("discount");
					String time_end = map.get("time_end");
					logger.info("签名验证成功");
					
					Date payTime = DateTimeUtils.formatString2Date(time_end, "yyyyMMddHHmmss");
					
					String payId = out_trade_no;
					PayStream stream = payStreamMapper.selectByPrimaryKey(payId);
					if(stream.getPayStatus() == 1){
						String xmlString ="<xml><return_code><![CDATA[SUCCESS]]></return_code>"+
								"<return_msg><![CDATA[OK]]></return_msg></xml> ";
						
						//response.getWriter().println(xmlString);
						return xmlString;
					}else{
						OrderInfoExample example = new OrderInfoExample();
						com.jsz.peini.bean.order.OrderInfoExample.Criteria criteria = example.createCriteria();
						criteria.andPayStreamIdEqualTo(payId);
						List<OrderInfo> titles = orderInfoMapper.selectByExample(example);
						if(titles.size()>=0){
							for(OrderInfo title : titles){
								//title.setOrderStatus(1);
								if(title.getOrderType() == 1 || title.getOrderType() == 3){
									if(title.getOrderStatus() == 0){
										title.setOrderStatus(1);
										title.setPayStatus(1);
										title.setPayTime(payTime);
										orderInfoMapper.updateByPrimaryKeySelective(title);
										boolean flag = orderInfoService.notifyPayOrder(title);
									}
								}else if(title.getOrderType() == 6 || title.getOrderType() == 7){
									if(title.getOrderStatus() == 0){
										title.setOrderStatus(2);
										title.setPayStatus(1);
										title.setPayTime(payTime);
										orderInfoMapper.updateByPrimaryKeySelective(title);
										boolean flag = orderInfoService.notifyPayOrder(title);
									}
								}else if(title.getOrderType() == OrderType.PARTY_PREPAY){
									partyService.setUserPrePayed(title);
								}else if(title.getOrderType() == OrderType.PARTY_ORDER || title.getOrderType() == OrderType.PARTY_PREPAY){
									partyService.setPartyPayed(title);
								}
							}
						}else{
							response.getWriter().print("fail");
						}
						stream.setPayType(2);
						stream.setFinishTime(payTime);
						stream.setPayStatus(1);
						stream.setTransactionCode(transaction_id);
						payStreamMapper.updateByPrimaryKey(stream);
						
						String xmlString ="<xml><return_code><![CDATA[SUCCESS]]></return_code>"+
								"<return_msg><![CDATA[OK]]></return_msg></xml> ";
						
						//response.getWriter().println(xmlString);
						return xmlString;
					}
					//return xmlString;
				}else {// MD5签名失败
					logger.info("微信支付异步通知 Md5签名失败");
				}
			}else{
				logger.info(map.get("return_msg"));
			}
        }catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		return null;
	}
	
	/**
	 * 转到统一下单
	 * @param title
	 * @return
	 * @throws Exception
	 */
	private String getWxOrder(JSONObject dataObj,String token,HttpServletRequest request,HttpServletResponse response,String trade_type) throws Exception {
		
		JSONObject object = new JSONObject();
		
		logger.info("****************转到统一下单***getWxOrder***********");
		
		//float sessionmoney = title.getPayPrice();
		double sessionmoney = dataObj.getDouble("payPrice");
		String finalmoney = String.valueOf(sessionmoney*100);
		finalmoney = finalmoney.replace(".00", "");
		finalmoney = finalmoney.replace(".0", "");
		//String finalmoney = "1";
		
		ResourceBundle PropertiesUtil = ResourceBundle.getBundle("config");
		
		// 商户号
		String partner = "";
		if(trade_type.equals("APP")){
			partner = PropertiesUtil.getString("wxapppay_partner");
		}else if(trade_type.equals("NATIVE")){
			partner = PropertiesUtil.getString("wxpay_partner");
		}
		// 密码
		String partnerkey = "";
		if(trade_type.equals("APP")){
			partnerkey = PropertiesUtil.getString("wxapppay_partnerkey");
		}else if(trade_type.equals("NATIVE")){
			partnerkey = PropertiesUtil.getString("wxpay_partnerkey");
		}
		
		// api密钥
		String key = "";
		if(trade_type.equals("APP")){
			key = PropertiesUtil.getString("wxapppay_paykey");
		}else if(trade_type.equals("NATIVE")){
			key = PropertiesUtil.getString("wxpay_paykey");
		}
		
		// 调用统一支付接口https://api.mch.weixin.qq.com/pay/unifiedorder  下单接口
		String strReq = createRandomString();
		//logger.info("aaa:"+strReq);
		
		String appid = "";
		if(trade_type.equals("APP")){
			appid = PropertiesUtil.getString("wxapp_appid");
		}else if(trade_type.equals("NATIVE")){
			appid = PropertiesUtil.getString("wx_appid");
		}
		
		String appsecret = "";
		if(trade_type.equals("APP")){
			appsecret = PropertiesUtil.getString("wxapp_appsecret");
		}else if(trade_type.equals("NATIVE")){
			appsecret = PropertiesUtil.getString("wx_appsecret");
		}
		
		// 商户号
		String mch_id = partner;
		// 子商户号 非必输
		// String sub_mch_id="";
		// 设备号 非必输
		String device_info = "";
		// 随机数
		String nonce_str = strReq;
		// 商品描述
		// String body = describe;
		
		// 商品描述根据情况修改
		//String body = title.getTitle();
		String body = dataObj.getString("title");
		// 附加数据,原样返回
		String attach = dataObj.getString("detail");
		// 商户订单号
		String out_trade_no = dataObj.getString("orderCode");
		
		// 总金额以分为单位，不带小数点
		// 订单生成的机器 IP
		String spbill_create_ip = request.getRemoteAddr();
		// 订 单 生 成 时 间 非必输
		// String time_start ="";
		// 订单失效时间 非必输
		// String time_expire = "";
		// 商品标记 非必输
		// String goods_tag = "";
		
		// 这里notify_url是 支付完成后微信发给该链接信息，可以判断会员是否支付成功，改变订单状态等。
		String notify_url = PeiniUtils.HOSTURL+"payWx/notify";
		//String notify_url = "http://renmgs.com/shop/notifyAction";
		
		String openid = "";
		// 非必输
		// String product_id = "";
		SortedMap<String, String> packageParams = new TreeMap<String, String>();
		packageParams.put("appid", appid);
		packageParams.put("mch_id", mch_id);
		packageParams.put("nonce_str", nonce_str);
		packageParams.put("body", body);
		packageParams.put("attach", attach);
		packageParams.put("out_trade_no", out_trade_no);
		
		// 这里写的金额为1 分到时修改
		packageParams.put("total_fee", finalmoney);
		packageParams.put("spbill_create_ip", spbill_create_ip);
		packageParams.put("notify_url", notify_url);
		
		packageParams.put("trade_type", trade_type);
		packageParams.put("openid", openid);
		packageParams.put("key", key);
		
		RequestHandler reqHandler = new RequestHandler(request, response);
		reqHandler.init(appid, appsecret, partnerkey);
		
		String sign = reqHandler.createSign(packageParams);
		String xml = "<xml>" + 
				"<appid>" + appid + "</appid>" + 
				"<attach>" + attach + "</attach>" + 
				"<body>" + body+ "</body>" +
				"<mch_id>" + mch_id + "</mch_id>" + 
				"<nonce_str>" + nonce_str + "</nonce_str>" + 
				"<notify_url>" + notify_url + "</notify_url>"+ 
				"<openid>" + openid + "</openid>" + 
				"<out_trade_no>" + out_trade_no + "</out_trade_no>"+
				"<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>" + 
				// 金额
				"<total_fee>" + finalmoney + "</total_fee>" +
				"<trade_type>" + trade_type + "</trade_type>" + 
				"<sign>" + sign + "</sign>" + 
				"</xml>";
		logger.info(xml);
		String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
		Map<String, Object> dataMap2 = new HashMap<String, Object>();
		String prepay_id = "";
		String code_url = "";
		try {
			com.jsz.peini.common.push.json.JSONObject prepayObj = new com.jsz.peini.common.push.json.JSONObject(new GetWxOrderno().getPayNo(createOrderURL, xml));
			logger.info(prepayObj.toString());
			if(prepayObj.getString("code").equals("0")){
				object.put("code", "0");
				object.put("msg", prepayObj.getString("msg"));
				return object.toString();
			}
			if(trade_type.equals("NATIVE")){
				code_url = prepayObj.getString("code_url");
			}
			//prepay_id = new GetWxOrderno().getPayNo(createOrderURL, xml);
			prepay_id = prepayObj.getString("prepay_id");
			logger.info("prepay_id:"+prepay_id);
			if (prepay_id.equals("")) {
				object.put("resultCode", "0");
				object.put("resultDesc", "统一支付接口获取预支付订单出错");
				//request.setAttribute("ErrorMsg", "统一支付接口获取预支付订单出错");
				//response.sendRedirect("/wxshop/error.jsp");
				return object.toString();
			}
			
			/*PayStream payStream = payStreamMapper.selectByPrimaryKey(out_trade_no);
			if(payStream != null){
				payStream.setPrepayId(prepay_id);
				payStreamMapper.updateByPrimaryKey(payStream);
			}*/
			
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		SortedMap<String, String> finalpackage = new TreeMap<String, String>();
		String timestamp = Sha1Util.getTimeStamp();
		nonce_str = createRandomString();
		//String packages = "prepay_id=" + prepay_id;
		String packages = "Sign=WXPay";
		finalpackage.put("appid", appid);
		finalpackage.put("partnerid", partner);
		finalpackage.put("prepayid", prepay_id);
		finalpackage.put("timestamp", timestamp);
		finalpackage.put("noncestr", nonce_str);
		finalpackage.put("package", packages);
		//finalpackage.put("signType", "MD5");
		finalpackage.put("key", key);
		
		String finalsign = reqHandler.createSign(finalpackage);
		logger.info("finalsign签名:" + finalsign);
		object.put("resultCode", "1");
		object.put("resultDesc", "");
		JSONObject dataObject = new JSONObject();
		dataObject.put("appid", appid);
		dataObject.put("partnerid", partner);
		dataObject.put("prepayid", prepay_id);
		dataObject.put("timestamp", timestamp);
		dataObject.put("noncestr", nonce_str);
		dataObject.put("package", packages);
		dataObject.put("sign", finalsign);
		dataObject.put("code_url", code_url);
		object.put("data", dataObject);
		
		/*
		title.setPayType(3);
		title.setPayStatus(0);
		title.setPayTime(new Date());
		orderTitleService.update(title);*/
		
		return object.toString();
	}
	
	/**
	 * 随机生成32位字符串
	 * @return
	 */
	public String createRandomString() {

		char ch[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
				'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1' };
		Random random = new Random();
		if (32 > 0) {
			int index = 0;
			char[] temp = new char[32];
			int num = random.nextInt();
			for (int i = 0; i < 32 % 5; i++) {
				temp[index++] = ch[num & 63];
				num >>= 6;

			}
			for (int i = 0; i < 32 / 5; i++) {
				num = random.nextInt();
				for (int j = 0; j < 5; j++) {
					temp[index++] = ch[num & 63];
					num >>= 6;
				}
			}
			return new String(temp, 0, 32);
		} else if (32 == 0) {
			return "";
		} else {
			throw new IllegalArgumentException();
		}
	} 
	
	@ResponseBody
	@RequestMapping(value = "/queryOrder",produces="text/plain;charset=UTF-8")
	public String queryOrder(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value="orderId",required=true) Long orderId
			) throws Exception{
		
		JSONObject object = new JSONObject();
			
		try{
			ResourceBundle PropertiesUtil = ResourceBundle.getBundle("config");
			String appid = PropertiesUtil.getString("wxapp_appid");
			String partner = PropertiesUtil.getString("wxapppay_partner");
			String nonce_str  = createRandomString();
			String key = PropertiesUtil.getString("wxapppay_paykey");
			
			OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId);
			
			String outTradeNo = orderInfo.getPayStreamId();
			
			QueryWeChatPayOrderReqModel reqModel = new QueryWeChatPayOrderReqModel();
			reqModel.setAppId(appid);
	        reqModel.setMchId(partner);
	        reqModel.setNonceStr(nonce_str);
	        reqModel.setOutTradeNo(outTradeNo);

	        String returnPaySign = reqModel.toString() + "&key=" + key;
	        String paySignEncry = com.jsz.peini.common.util.wxpay.query.MD5Util.encryptMD5(returnPaySign).toUpperCase();
	        QueryWeChatPayOrderResModel resModel = null;
	        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
	        String list = reqModel.toString() + "&sign=" + paySignEncry;
	        for (String B : list.split("&")) {
	            map.put(B.split("=")[0], B.split("=")[1]);
	        }
	        try {
	            String resultXML = WeChatUtil.sendGet("https://api.mch.weixin.qq.com/pay/orderquery", com.jsz.peini.common.util.wxpay.query.XMLUtil.getXMLForMap(map),
	                    false, WeChatUtil.ENCODE);
	            logger.info(resultXML);
	            /*Map<String, String> resultMap = com.jsz.peini.common.util.wxpay.query.XMLUtil.doXMLParse(resultXML);
	            resModel = buildQueryWeChatPayOrderResModel(resultMap);*/
	            
	            net.sf.json.JSONObject oo = com.jsz.peini.common.util.wxpay.query.XMLUtil.doXMLParse(resultXML);
	            resModel = buildQueryWeChatPayOrderResModelFromJson(oo);
	            //resModel = (QueryWeChatPayOrderResModel)net.sf.json.JSONObject.toBean(oo, QueryWeChatPayOrderResModel.class);
	            
	            if(resModel.getTradeState().equals("SUCCESS")){
					// 腾讯订单号
	            	String transaction_id = resModel.getTransactionId();
	            	// 金额,以分为单位
					String total_fee = resModel.getTotalFee();
					
					PayStream stream = payStreamMapper.selectByPrimaryKey(outTradeNo);
					
					if(stream == null){
						object.put("resultCode", Constants.FAIL);
						object.put("resultDesc", "没有查到订单");
						return object.toJSONString();
					}
					
					if(stream.getPayStatus() == 1){
						OrderInfoExample example = new OrderInfoExample();
						com.jsz.peini.bean.order.OrderInfoExample.Criteria criteria = example.createCriteria();
						criteria.andPayStreamIdEqualTo(outTradeNo);
						List<OrderInfo> titles = orderInfoMapper.selectByExample(example);
						if(titles.size()>=0){
							for(OrderInfo title : titles){
								if(title.getOrderType() == 1 || title.getOrderType() == 3){
									if(title.getPayStatus() == 0){
										if(title.getOrderStatus() == 0){
											title.setOrderStatus(1);
										}
										if(title.getPayStatus() == 0){
											title.setPayStatus(1);
										}
										title.setPayTime(new Date(Long.parseLong(resModel.getTimeEnd())));
										//boolean flag = orderInfoService.notifyPayOrder(title);
										
										//RedisUtil.lpush(RedisConstants.ORDER_NOTIFY.getBytes(), SerializeUtil.serialize(title));
									}
								}else if(title.getOrderType() == 6){
									if(title.getPayStatus() == 0){
										title.setOrderStatus(2);
										title.setPayStatus(1);
										title.setPayTime(new Date());
										//boolean flag = orderInfoService.notifyPayOrder(title);
										
										//RedisUtil.lpush(RedisConstants.ORDER_NOTIFY.getBytes(), SerializeUtil.serialize(title));
									}
								}
							}
						}else{
							//response.getWriter().print("fail");
						}
						
						object.put("resultCode", Constants.SUCCESS);
						object.put("resultDesc", Constants.SUCCESS_DESC);
						return object.toJSONString();
					}else{
						OrderInfoExample example = new OrderInfoExample();
						com.jsz.peini.bean.order.OrderInfoExample.Criteria criteria = example.createCriteria();
						criteria.andPayStreamIdEqualTo(outTradeNo);
						List<OrderInfo> titles = orderInfoMapper.selectByExample(example);
						if(titles.size()>=0){
							for(OrderInfo title : titles){
								if(title.getOrderType() == 1 || title.getOrderType() == 3){
									if(title.getOrderStatus() == 0){
										title.setOrderStatus(1);
										title.setPayStatus(1);
										title.setPayTime(new Date());
										//boolean flag = orderInfoService.notifyPayOrder(title);
										
										//RedisUtil.lpush(RedisConstants.ORDER_NOTIFY.getBytes(), SerializeUtil.serialize(title));
									}
								}else if(title.getOrderType() == 6){
									if(title.getOrderStatus() == 0){
										title.setOrderStatus(2);
										title.setPayStatus(1);
										title.setPayTime(new Date());
										//boolean flag = orderInfoService.notifyPayOrder(title);
										
										//RedisUtil.lpush(RedisConstants.ORDER_NOTIFY.getBytes(), SerializeUtil.serialize(title));
									}
								}
							}
						}else{
							//response.getWriter().print("fail");
						}
						stream.setPayType(2);
						stream.setFinishTime(new Date());
						stream.setPayStatus(1);
						stream.setTransactionCode(transaction_id);
						payStreamMapper.updateByPrimaryKey(stream);
					}
	            	
					object.put("resultCode", Constants.SUCCESS);
					object.put("resultDesc", Constants.SUCCESS_DESC);
					return object.toJSONString();
	            }
	        } catch (Exception e) {
	            logger.error(e.getMessage(),e);
	        }
			
		}catch(Exception e){
			return null;
		}
		return object.toString();
	}
	
	private QueryWeChatPayOrderResModel buildQueryWeChatPayOrderResModel(Map<String, String> resultMap) {
        
        QueryWeChatPayOrderResModel resModel = new QueryWeChatPayOrderResModel();
        resModel.setTradeState(resultMap.get("trade_state"));
        resModel.setIsSubscribe(resultMap.get("is_subscribe"));
        resModel.setAppId(resultMap.get("appid"));
        resModel.setFeeTypel(resultMap.get("fee_type"));
        resModel.setOutTradeNo(resultMap.get("out_trade_no"));
        resModel.setNonceStr(resultMap.get("nonce_str"));
        resModel.setTransactionId(resultMap.get("transaction_id"));
        resModel.setTradeType(resultMap.get("trade_type"));
        resModel.setSign(resultMap.get("sign"));
        resModel.setMchId(resultMap.get("mch_id"));
        resModel.setAttach(resultMap.get("attach"));
        resModel.setTotalFee(resultMap.get("total_fee"));
        resModel.setTimeEnd(resultMap.get("time_end"));
        resModel.setOpenId(resultMap.get("openid"));
        resModel.setReturnCode(resultMap.get("return_code"));
        resModel.setBankType(resultMap.get("bank_type"));
        resModel.setCashFee(resultMap.get("cash_fee"));

        return resModel;
    }
	
	private QueryWeChatPayOrderResModel buildQueryWeChatPayOrderResModelFromJson(net.sf.json.JSONObject resultMap) {
        
        QueryWeChatPayOrderResModel resModel = new QueryWeChatPayOrderResModel();
        resModel.setTradeState(resultMap.get("trade_state").toString());
        resModel.setIsSubscribe(resultMap.get("is_subscribe").toString());
        resModel.setAppId(resultMap.get("appid").toString());
        resModel.setFeeTypel(resultMap.get("fee_type").toString());
        resModel.setOutTradeNo(resultMap.get("out_trade_no").toString());
        resModel.setNonceStr(resultMap.get("nonce_str").toString());
        resModel.setTransactionId(resultMap.get("transaction_id").toString());
        resModel.setTradeType(resultMap.get("trade_type").toString());
        resModel.setSign(resultMap.get("sign").toString());
        resModel.setMchId(resultMap.get("mch_id").toString());
        resModel.setAttach(resultMap.get("attach").toString());
        resModel.setTotalFee(resultMap.get("total_fee").toString());
        resModel.setTimeEnd(resultMap.get("time_end").toString());
        resModel.setOpenId(resultMap.get("openid").toString());
        resModel.setReturnCode(resultMap.get("return_code").toString());
        resModel.setBankType(resultMap.get("bank_type").toString());
        resModel.setCashFee(resultMap.get("cash_fee").toString());

        return resModel;
    }
}
